package io.github.maojian.stack;

import org.junit.Test;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.Stack;

/**
 * @Auther: jian.mao
 * @Date: 2022-07-13 09:19
 * @Description: 735. 行星碰撞
 *
 * https://leetcode.cn/problems/asteroid-collision/
 */
public class Q735 {

    Deque<Integer> stack = new ArrayDeque<>();

    public int[] asteroidCollision(int[] asteroids) {
        int length = asteroids.length;
        for (int i = 0; i < length; i++) {
            int curAsterOids = asteroids[i];
            add(curAsterOids);
        }

        int size = stack.size();

        int[] rtn = new int[size];
        for (int i = size - 1; i >= 0; i--) {
            rtn[i] = stack.pop();
        }
        return rtn;
    }

    public void add(int curAsterOids) {
        if (stack.isEmpty()) {
            stack.push(curAsterOids);
            return;
        }
        int preAsterOids = stack.peek();

        if (preAsterOids < 0) {
            stack.push(curAsterOids);
            return;
        }

        if (curAsterOids > 0){
            stack.push(curAsterOids);
            return;
        }

        int curAsterOidsAbs = Math.abs(curAsterOids);

        if (curAsterOidsAbs == preAsterOids){
            stack.pop();
            return;
        }

        if (curAsterOidsAbs > preAsterOids){
            stack.pop();
            add(curAsterOids);
        }
    }

    @Test
    public void test() {
        int[] asteroids = new int[]{-2, -1, 1, 2};
        Arrays.stream(asteroidCollision(asteroids)).forEach(System.out::print);
    }

}
